import React, { useEffect } from 'react';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';
import { useLocation } from 'react-router-dom';
import useStores from './useStores';


export const useNProgres = () => {
    const location = useLocation();
    const [count, setCount] = React.useState(0);
    const { show_top_progress, color_primary } = useStores();
    const setNProgressColor = (color: string) => {
        const style = document.createElement('style');
        style.innerHTML = `
            #nprogress .bar {
                background: ${color} !important;
            }
        `;
        document.head.appendChild(style);
    };

    if (count == 0) {
        NProgress.configure({
            showSpinner: false,
        });
        setTimeout(() => {
            NProgress.done(true);
        }, 0);
    }

    useEffect(() => {
        setCount(count + 1);
        if (!show_top_progress) return () => {
            NProgress.done();
        };
        NProgress.start();

        setNProgressColor(color_primary);

        return () => {
            setTimeout(() => {
                NProgress.done(true);
            }, 800);
        };
    }, [location]);
}